/**
 * User: swi
 * Date: 21/06/11
 * Time: 21.02
 */
package thetvdb

import "fmt"
import "http"
import "xml"
import "os"

type TheTVDB struct {
    url string
    apiUrl string
    apiKey string
    cache Cache
    Language string
}

func Init(apiKey string) (*TheTVDB, os.Error) {
    tv := &TheTVDB{}
    tv.Language = "en"
    tv.cache = InitSessionCache()
    tv.apiKey = apiKey
    err := tv.init()
    return tv, err
}

func (tv *TheTVDB) init() (err os.Error) {

    data := new(Mirrors)
    if err := tv.fetchXml("http://thetvdb.com/api/" + tv.apiKey + "/mirrors.xml", data); err == nil {
        for _, mirror := range(data.Mirror) {
            tv.url = mirror.Mirrorpath + "/api"
            tv.apiUrl = tv.url + "/" + tv.apiKey
        }
    }
    return
}

func (tv *TheTVDB) fetchXml(url string, val interface{}) (err os.Error) {
    client := new(http.Client)
    fmt.Println("Getting: " + url)
    if r, _, err := client.Get(url); err == nil {
        defer r.Body.Close()
        err = xml.Unmarshal(r.Body, val)
    }
    return
}

func (tv *TheTVDB) FindSeries(title string) (series []SimpleSeries) {
    data := new(Data)
    fetchUrl := tv.url + "/GetSeries.php?seriesname=" + title
    if err := tv.fetchXml(fetchUrl, data); err == nil {
        series = data.Series
    }
    return
}
func (tv *TheTVDB) GetSeriesById(id string) (series *Series) {
    if cachedSeries, ok := tv.cache.HasSeries(id); ok {
        series = cachedSeries
    } else {
        data := new(SeriesData)
        url := tv.apiUrl + "/series/" + id + "/all/" + tv.Language + ".xml"
        if err := tv.fetchXml(url, data); err == nil {
            series = &data.Series
            for _, ep := range(data.Episode) {
                fmt.Println(ep)
            }
            tv.cache.PutSeries(series)
        }
    }
    return

}

func (tv *TheTVDB) GetSeries(simpleSeries *SimpleSeries) (series *Series) {
    return tv.GetSeriesById( simpleSeries.Id )
}


